import logging

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from taunt.taunt_serializers import SpitUitSerializer, CollectSpitSerializer
from users.models import Spit

logger = logging.getLogger('taunt_views')

# 收藏或取消收藏，点赞或取消点赞
class UpdateSpitViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = CollectSpitSerializer
    message = None

    # 点赞或取消点赞
    def update_thumbup(self, request, *args, **kwargs):
        spit = self.get_object()
        spit_id = kwargs.get('pk')
        return_dict = {}
        message = None
        user_id = request.user.id
        redis_conn = get_redis_connection('like')
        like_flag = redis_conn.hget(f"{spit_id}_like", user_id)
        try:
            if like_flag:
                spit.thumbup -= 1
                redis_conn.hdel(f"{spit_id}_like", user_id)
                message = "取消点赞成功"
            else:
                spit.thumbup += 1
                redis_conn.hset(f"{spit_id}_like", user_id, 1)
                message = "点赞成功"

            return_dict["message"] = message
            return_dict["success"] = True
        except ConnectionError as e:
            logger.info(e)
            return_dict["success"] = False
        finally:
            return_dict["message"] = message
        return Response(return_dict)

    # 收藏或取消收藏
    def update_collect(self, request, *args, **kwargs):
        spit_id = kwargs.get('pk')
        return_dict = {}
        message = None
        user_id = request.user.id
        redis_conn = get_redis_connection('collection')
        collect_status = redis_conn.hget(f"{spit_id}_collect", user_id)

        try:
            if collect_status:
                redis_conn.hdel(f"{spit_id}_collect", user_id)
                message = "取消收藏成功"
            else:
                redis_conn.hset(f"{spit_id}_collect", user_id, 1)
                message = "收藏成功"

            return_dict["message"] = message
            return_dict["success"] = True

        except ConnectionError as e:
            logger.info(e)
            return_dict["success"] = False
        finally:
            return_dict["message"] = message
        return Response(return_dict)

# 获取吐槽列表视图集
# class SpitViewSet(ModelViewSet):
#     queryset = Spit.objects.all()
#     serializer_class = SpitUitSerializer
#
#     # 获取吐槽信息不需要登录，重写perform_authentication
#     def perform_authentication(self, request):
#         pass












